package org.jeecg.modules.inspect.controller;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.inspect.entity.InsLine;
import org.jeecg.modules.inspect.entity.InsLinePoint;
import org.jeecg.modules.inspect.entity.InsPoint;
import org.jeecg.modules.inspect.service.IInsLinePointService;
import org.jeecg.modules.inspect.service.IInsLineService;
import org.jeecg.modules.inspect.service.IInsPointService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

 /**
 * @Description: 线路
 * @Author: jeecg-boot
 * @Date:   2023-11-24
 * @Version: V1.0
 */
@Api(tags="线路")
@RestController
@RequestMapping("/inspect/insLine")
@Slf4j
public class InsLineController extends JeecgController<InsLine, IInsLineService> {

	@Autowired
	private IInsLineService insLineService;

	 @Autowired
	 private IInsPointService insPointService;

	@Autowired
	private IInsLinePointService insLinePointService;


	/*---------------------------------主表处理-begin-------------------------------------*/

	/**
	 * 分页列表查询
	 * @param insLine
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "线路-分页列表查询")
	@ApiOperation(value="线路-分页列表查询", notes="线路-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<InsLine>> queryPageList(InsLine insLine,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<InsLine> queryWrapper = QueryGenerator.initQueryWrapper(insLine, req.getParameterMap());
		Page<InsLine> page = new Page<InsLine>(pageNo, pageSize);
		IPage<InsLine> pageList = insLineService.page(page, queryWrapper);

		return Result.OK(pageList);
	}

	/**
     *   添加
     * @param insLine
     * @return
     */
    @AutoLog(value = "线路-添加")
    @ApiOperation(value="线路-添加", notes="线路-添加")
    //@RequiresPermissions("org.jeecg.modules:ins_line:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody InsLine insLine) {
        insLineService.save(insLine);
        return Result.OK("添加成功！");
    }

    /**
     *  编辑
     * @param insLine
     * @return
     */
    @AutoLog(value = "线路-编辑")
    @ApiOperation(value="线路-编辑", notes="线路-编辑")
    //@RequiresPermissions("org.jeecg.modules:ins_line:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
    public Result<String> edit(@RequestBody InsLine insLine) {
        insLineService.updateById(insLine);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     * @param id
     * @return
     */
    @AutoLog(value = "线路-通过id删除")
    @ApiOperation(value="线路-通过id删除", notes="线路-通过id删除")
    //@RequiresPermissions("org.jeecg.modules:ins_line:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name="id",required=true) String id) {
        insLineService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @AutoLog(value = "线路-批量删除")
    @ApiOperation(value="线路-批量删除", notes="线路-批量删除")
    //@RequiresPermissions("org.jeecg.modules:ins_line:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
        this.insLineService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 导出
     * @return
     */
    //@RequiresPermissions("org.jeecg.modules:ins_line:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, InsLine insLine) {
        return super.exportXls(request, insLine, InsLine.class, "线路");
    }

    /**
     * 导入
     * @return
     */
    //@RequiresPermissions("org.jeecg.modules:ins_line:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, InsLine.class);
    }
	/*---------------------------------主表处理-end-------------------------------------*/


    /*--------------------------------子表处理-线路点位-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * @return
	 */
	//@AutoLog(value = "线路点位-通过主表ID查询")
	@ApiOperation(value="线路点位-通过主表ID查询", notes="线路点位-通过主表ID查询")
	@GetMapping(value = "/listInsLinePointByMainId")
    public Result<IPage<InsLinePoint>> listInsLinePointByMainId(InsLinePoint insLinePoint,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        QueryWrapper<InsLinePoint> queryWrapper = QueryGenerator.initQueryWrapper(insLinePoint, req.getParameterMap());
        Page<InsLinePoint> page = new Page<InsLinePoint>(pageNo, pageSize);
        IPage<InsLinePoint> pageList = insLinePointService.page(page, queryWrapper);
		pageList.getRecords().stream().forEach(item -> {
			InsPoint insPoint = insPointService.getById(item.getPointId());
			if(null != insPoint) {
				item.setPointName(insPoint.getPointName());
			}
		});

        return Result.OK(pageList);
    }

	/**
	 * 添加
	 * @param insLinePoint
	 * @return
	 */
	@AutoLog(value = "线路点位-添加")
	@ApiOperation(value="线路点位-添加", notes="线路点位-添加")
	@PostMapping(value = "/addInsLinePoint")
	public Result<String> addInsLinePoint(@RequestBody InsLinePoint insLinePoint) {
		List<InsLinePoint> list = insLinePointService.list(Wrappers.<InsLinePoint>lambdaQuery()
				.eq(InsLinePoint::getPointId, insLinePoint.getPointId())
				.eq(InsLinePoint::getLineId, insLinePoint.getLineId()));

		if(CollUtil.isNotEmpty(list)) {
			return Result.error("该点位已存在！");
		}
		insLinePointService.save(insLinePoint);
		return Result.OK("添加成功！");
	}

    /**
	 * 编辑
	 * @param insLinePoint
	 * @return
	 */
	@AutoLog(value = "线路点位-编辑")
	@ApiOperation(value="线路点位-编辑", notes="线路点位-编辑")
	@RequestMapping(value = "/editInsLinePoint", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> editInsLinePoint(@RequestBody InsLinePoint insLinePoint) {
		InsLinePoint oldLinePoint = insLinePointService.getById(insLinePoint.getId());

		if(!oldLinePoint.getPointId().equals(insLinePoint.getPointId())) {
			List<InsLinePoint> list = insLinePointService.list(Wrappers.<InsLinePoint>lambdaQuery()
					.eq(InsLinePoint::getPointId, insLinePoint.getPointId())
					.eq(InsLinePoint::getLineId, insLinePoint.getLineId()));

			if(CollUtil.isNotEmpty(list)) {
				return Result.error("该点位已存在！");
			}
		}

		insLinePointService.updateById(insLinePoint);
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "线路点位-通过id删除")
	@ApiOperation(value="线路点位-通过id删除", notes="线路点位-通过id删除")
	@DeleteMapping(value = "/deleteInsLinePoint")
	public Result<String> deleteInsLinePoint(@RequestParam(name="id",required=true) String id) {
		insLinePointService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "线路点位-批量删除")
	@ApiOperation(value="线路点位-批量删除", notes="线路点位-批量删除")
	@DeleteMapping(value = "/deleteBatchInsLinePoint")
	public Result<String> deleteBatchInsLinePoint(@RequestParam(name="ids",required=true) String ids) {
	    this.insLinePointService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportInsLinePoint")
    public ModelAndView exportInsLinePoint(HttpServletRequest request, InsLinePoint insLinePoint) {
		 // Step.1 组装查询条件
		 QueryWrapper<InsLinePoint> queryWrapper = QueryGenerator.initQueryWrapper(insLinePoint, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 // Step.2 获取导出数据
		 List<InsLinePoint> pageList = insLinePointService.list(queryWrapper);
		 List<InsLinePoint> exportList = null;

		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		 } else {
			 exportList = pageList;
		 }

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 //此处设置的filename无效,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.FILE_NAME, "线路点位");
		 mv.addObject(NormalExcelConstants.CLASS, InsLinePoint.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("线路点位报表", "导出人:" + sysUser.getRealname(), "线路点位"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		 return mv;
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importInsLinePoint/{mainId}")
    public Result<?> importInsLinePoint(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
       // 获取上传文件对象
			 MultipartFile file = entity.getValue();
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<InsLinePoint> list = ExcelImportUtil.importExcel(file.getInputStream(), InsLinePoint.class, params);
				 for (InsLinePoint temp : list) {
                    temp.setLineId(mainId);
				 }
				 long start = System.currentTimeMillis();
				 insLinePointService.saveBatch(list);
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 return Result.OK("文件导入成功！数据行数：" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-线路点位-end----------------------------------------------*/




}
